#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define TOLOWER(x) ((x) | 0x20)
#define isxdigit(c) (('0' <= (c) && (c) <= '9') || ('a' <= (c) && (c) <= 'f') || ('A' <= (c) && (c) <= 'F'))
#define isdigit(c) ('0' <= (c) && (c) <= '9')

char charadd(char c)
{
    if(('0' <= c && c <= '8') || ('a' <= c && c <= 'e') || ('A' <= c && c <= 'E'))
    {
        return c + 1;
    }
    else if(c == '9')
    {
        return 'A';
    }
    else
    {
        return '0';
    }
}

int main(int argc, char **argv)
{
    FILE *fp;
    int i;
    char mac[13];
    char cmd[50];
    char buff[256];
    fp = fopen("error.txt", "r");
    if(fp != NULL)
    {
    	fclose(fp);
        system("rm -f ./error.txt");
    }
    if(argc != 3)
    {
        printf("Arg Error!!\n");
        system("echo error > error.txt");
        return 1;
    }
    
    //vertify mac
    if(strlen(argv[2]) == 12)
    {
        for(i = 0; i < 12; i++)
        {
            if(!isxdigit(argv[2][i]))
            {
                printf("Arg Error!!\n");
                system("echo error > error.txt");
                return 1;
            }
        }
    }
    else
    {
        printf("Arg Error!!\n");
        system("echo error > error.txt");
        return 1;
    }
    
    
    memset(mac, 0x00, sizeof(mac));
    memset(cmd, 0x00, sizeof(cmd));
    strcpy(mac, argv[2]);
    //mac add
    if(strcmp("-a", argv[1]) == 0)
    {
        for(i = 11; i >= 0; i--)
        {
            mac[i] = charadd(mac[i]);
            if(mac[i] != '0');
            {
                break;
            }
        }
        strcpy(cmd, "echo ");
        strcat(cmd, mac);
        strcat(cmd, " > addrfile.dat");
        system(cmd);
    }
    //mac log check
    else if(strcmp("-c", argv[1]) == 0)
    {
    	fp = fopen("MAC.LOG", "r");
    	if(fp == NULL)
    	{
	    return 0;
    	}
    	while(fgets(buff, 256, fp))
    	{
    	    if(strlen(buff) < 12)
    	    {
    	        printf("MAC.LOG error!\n");
    	        system("echo error > error.txt");
    	        fclose(fp);
                return 1;
    	    }
    	    for(i = 0; i < 12; i++)
    	    {
    	        if(TOLOWER(buff[i]) != TOLOWER(mac[i]))
    	        {
    	            break;
    	        }
    	    }
    	    if(i == 12)
    	    {
    	        printf("MAC check error!\n");
    	        system("echo error > error.txt");
    	        fclose(fp);
                return 1;
    	    }
    	}
    	fclose(fp);
    }
    //mac log
    else if(strcmp("-l", argv[1]) == 0)
    {
    	strcpy(cmd, "echo ");
    	strcat(cmd, mac);
    	strcat(cmd, " >> MAC.LOG");
    	system(cmd);
    }
    else
    {
        printf("Arg Error!!\n");
        system("echo error > error.txt");
        return 1;
    }
    return 0;
}
